package pers.cz.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.netty.handler.HeartBeatHandler;
import pers.cz.netty.handler.IdleStateHandler;
import pers.cz.netty.handler.MessageHandler;
import pers.cz.netty.protocal.*;

/**
 * @program: PostGirl-panent
 * @description: 客户端触发类
 * @author: Cheng Zhi
 * @create: 2022-10-04 15:03
 **/
public class NettyClient {

    private static final Logger log = LoggerFactory.getLogger(NettyClient.class);

    private String hosts;

    private Integer port;

    private Bootstrap bootstrap;

    private static Channel channel;

    private HeartBeatHandler heartBeatHandler = new HeartBeatHandler(this);

    EventLoopGroup group = new NioEventLoopGroup();

    public NettyClient(String hosts, Integer port) {
        showBanner();
        this.hosts = hosts;
        this.port = port;
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>(){

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(ProtocalConst.PACKAGE_MAX_SIZE, 9, 8, 0, 0));
                        // 解决粘包问题
                        //ByteBuf delimiter = Unpooled.copiedBuffer("$POSTGIRL$".getBytes());
                        //socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(ProtocalConst.PACKAGE_MAX_SIZE, delimiter));
                        socketChannel.pipeline().addLast(new MessageDecoder());
                        socketChannel.pipeline().addLast(new MessageEncoder());
                        socketChannel.pipeline().addLast(heartBeatHandler);
                        socketChannel.pipeline().addLast(new MessageHandler());
                        socketChannel.pipeline().addLast(new IdleStateHandler());

                    }
                });
    }

    public ChannelFuture connect() {

        synchronized (this) {
            final ChannelFuture f = bootstrap.connect(this.hosts, this.port);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        channel = future.channel();
                    } else {
                        future.channel().pipeline().fireChannelInactive();
                    }
                }
            });
            return f;
        }
    }

    public void shutDown() {
        if (group != null) {
            group.shutdownGracefully();
        }
    }

    public static boolean send(Message message) {
        if (channel == null || !channel.isActive()) {
            log.debug("未连接服务器，发送失败");
            return false;
        }

        ChannelFuture f = channel.writeAndFlush(message);
        return f.isSuccess();
    }

    public void showBanner() {
        log.info("================================================================================");
        log.info("==     ~~~   postGirl netty client is starting    ~~~                         ==");
        log.info("================================================================================");
    }

   /* public static void main(String[] args) throws InterruptedException {
        final ChannelFuture connect = new NettyClient("127.0.0.1", 8881).connect();
        if (connect.sync().isSuccess()) {
            Message message = new Message();
            message.setMsgType(MsgType.DATA);
            message.setContent("hello world");
            send(message);
        }

    }*/
}
